/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.common.service;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.beetl.sql.core.db.KeyHolder;
import org.jbase.common.entity.BaseEntity;
import org.jbase.common.utils.Pager;

/**
 * Project: fw_admin <br/>
 * File: EntityService.java <br/>
 * Class: com.yxt.admin.service.sys.EntityService <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: http://www.yxtsoft.com/ <br/>
 * Makedate: 2015年12月19日 下午2:50:38 <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
public abstract class EntityService<T extends BaseEntity> extends BaseService {

	/**
	 * 
	 * 描述 : 用来设置实体类的Class. <br/>
	 * <p>
	 * 
	 * @return
	 */
	abstract protected Class<T> clzz();

	public Pager listWithPage(Map<String, String> map, Pager pager) {
		pager = listWithPageList("common.count", "common.searchAndPager", map, pager);
		return pager;
	}

	protected Map<String, Object> listWithPageWhere(Map<String, String> map) {
		StringBuilder sb = new StringBuilder(" 1=1 ");
		for (String key : map.keySet()) {
			sb.append(" and " + key + " like '%" + map.get(key) + "%'");
		}
		String tableName = sqlManager.getNc().getTableName(clzz());
		Map<String, Object> where = new HashMap<String, Object>();
		where.put("table_name", tableName);
		where.put("sql_where", sb.toString());
		return where;
	}

	protected Pager listWithPageList(String sqlidCount, String sqlidList, Map<String, String> map, Pager pager) {
		Map<String, Object> where = listWithPageWhere(map);
		Integer recordCount = sqlManager.intValue(sqlidCount, where);
		pager.setRecordCount(recordCount);
		List<T> list = sqlManager.select(sqlidList, clzz(), where, pager.getStart(), pager.getPageSize());
		pager.setList(list);
		return pager;
	}

	public int insertHolderId(Map<String, Object> map) {
		KeyHolder keyHolder = new KeyHolder();
		try {
			T t = clzz().newInstance();
			BeanUtils.populate(t, map);
			sqlManager.insert(clzz(), t, keyHolder);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		Map<String, Object> paras = new HashMap<String, Object>();
//		paras.put("sid", UUID.randomUUID().toString());
//		paras.put("lockVersion", 0);
//		paras.put("createTime", new Date());
//		paras.put("state", 1);
//		paras.put("isEnable", 1);
//		paras.put("isDelete", 0);
//		paras.putAll(map);
		return keyHolder.getInt();
	}

	public int insert(Object paras) {
		return sqlManager.insert(clzz(), paras);
	}

	public int deleteById(int id) {
		return sqlManager.deleteById(clzz(), id);
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param ids
	 */
	public void deleteByIds(String ids) {
		if (ids.endsWith(","))
			ids = ids.substring(0, ids.length() - 1);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", sqlManager.getNc().getTableName(clzz()));
		map.put("ids", ids);
		sqlManager.update("common.deleteByIds", map);
	}

	public void deleteBySid(String sid) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("table_name", sqlManager.getNc().getTableName(clzz()));
		map.put("sid", sid);
		sqlManager.update("common.deleteBySid", map);
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param warpRequest
	 * @return
	 */
	public int update(Map<String, Object> map) {
		StringBuilder sb = new StringBuilder("update ");
		sb.append(sqlManager.getNc().getTableName(clzz()));
		sb.append(" set ");
		for (String key : map.keySet()) {
			if ("id".equals(key) || "sid".equals(key))
				continue;
			sb.append(key + "=#" + key + "#,");
		}
		sb.deleteCharAt(sb.lastIndexOf(",")).append(" where id = #id#");
		return sqlManager.executeUpdate(sb.toString(), map);
	}

	public int updateBySid(String sid, Map<String, Object> map) {
		map.put("sid", sid);
		StringBuilder sb = new StringBuilder("update ");
		sb.append(sqlManager.getNc().getTableName(clzz()));
		sb.append(" set ");
		for (String key : map.keySet()) {
			if ("id".equals(key) || "sid".equals(key))
				continue;
			sb.append(key + "=#" + key + "#,");
		}
		sb.deleteCharAt(sb.lastIndexOf(",")).append(" where sid = #sid#");
		return sqlManager.executeUpdate(sb.toString(), map);
	}

	public T fetchById(int id) {
		return sqlManager.unique(clzz(), id);
	}

	public T fetchBySid(String sid) {
		Map<String, String> paras = new HashMap<String, String>();
		paras.put("table_name", sqlManager.getNc().getTableName(clzz()));
		paras.put("sid", sid);
		return sqlManager.selectSingle("common.selectSingleBySid", paras, clzz());
	}

	public T fetchByCol(Map<String, Object> map) {
		List<T> list = findByCol(map);
		return list == null ? null : list.get(0);
	}

	public List<T> findByCol(Map<String, Object> map) {
		StringBuilder sb = new StringBuilder("select * from ");
		sb.append(sqlManager.getNc().getTableName(clzz()));
		sb.append(" where 1=1 ");
		for (String key : map.keySet()) {
			sb.append(" and " + key + "= #" + key + "# ");
		}
		List<T> list = sqlManager.execute(sb.toString(), clzz(), map);
		return list.isEmpty() ? null : list;
	}

	public List<T> list() {
		return sqlManager.all(clzz());
	}

}
